import {Component, ViewChild} from '@angular/core';
import {IonicPage, NavController, NavParams, Platform} from 'ionic-angular';
import {TabsPage} from '../tabs/tabs.page';
import {SecureStorageService} from '../../../../shared/services/secure-storage.services';
import {HttpService} from 'http-service';
import {UtilsService} from '../../../../shared/services/utils.services';
import {API} from '../../../../shared/models/api-path-extension';
import {Subscription, Observable, Subscriber} from 'rxjs';
import {EncryptService} from "../../../../shared/services/encrypt.service";
import {SyncService} from '../../../../shared/services/offline/sync.servie';
import {SqliteService} from "../../../../shared/services/sqliteDB/sqlite.service";
import {NetStatus} from "../../../../shared/services/offline/sync-push.service";
import {HomePage} from "../home/home.page";
import {Network} from "@ionic-native/network";
import {RefreshTokenService} from "../../../../shared/services/refresh-token.service";
import {Device} from "@ionic-native/device";
import {flatMap} from "rxjs/operators";

/**
 * Generated class for the QixinLoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */


declare var window: {
  cordova: any;
  plugin: any;
  localStorage: {
    setItem: any,
    getItem: any
  }
};

declare const ENV: {
  environment: any,
  baseUrl: any
};

declare let navigator: any;

@IonicPage()
@Component({
  selector: 'page-qixin-login',
  templateUrl: 'qixin-login.page.html',
})
export class QixinLoginPage {
  userName: string = "";
  passWord: string = "";
  // userName: string = "luojun0807@gzgy.csg.cn";
  // userName: string = "user_cQdR2E";
  // passWord: string = "Gzdw@4321";
  // userName: string = "user_0c0j5y";
  // passWord: string = "Gzdw@4321";
  role: string;
  loadingIndex: number;
  frequency: number = 1;
  private disposable: Subscription;

  constructor(public plt: Platform,
              public navCtrl: NavController,
              public navParams: NavParams,
              private httpService: HttpService,
              private synService: SyncService,
              private db: SqliteService,
              private network: Network,
              private device: Device,
              private refreshToken: RefreshTokenService,
              public encryptService: EncryptService,
              private storage: SecureStorageService,
              public util: UtilsService) {
    this.storage.get("loginAccount").subscribe((account) => {
      if (account) {
        this.userName = account;
      }
    });
    if (new RegExp(network.type).test(NetStatus.work) || !this.device.cordova) {
      this.storage.get('access_token').subscribe((res) => {
        if (res) {
          this.util.showLoading();
          this.refreshToken.refreshToken()
            .subscribe(() => {
              this.storage.get("loginAccount").subscribe((account) => {
                this.db.getDb(account).then(() => {
                  this.synService.openDatabase()
                    .subscribe(() => {
                      this.util.hiddenLoading();
                      this.navCtrl.setRoot(TabsPage, {role: window.localStorage.getItem("role")});
                    });
                });
              });

            }, (error) => {
              // TODO TOKEN
              this.util.hiddenLoading();
            });

        } else {
          // this.db.reset().subscribe(() => {
          //   // TODO
          // });
        }
      });
    }

    this.disposable = this.httpService.onError.subscribe((error: { status: number }) => {
      if (error && error.status === 401) {
        this.disposable.unsubscribe();
        // TODO we'd better present a login page overlay the current page.
        this.navCtrl.setRoot(QixinLoginPage);
      }
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad QixinLoginPage');
    this.frequency = 1;
    let ob: Observable<any>;
    ob = this.encryptService.getPublic();
    ob.subscribe(() => {
      console.log("alread get public key");
    });

  }

  invokeLogin(name, pwd, callback?) {

    let args = {
      grant_type: "password",
      loginAccount: name,
      loginPassword: this.encryptService.encrypt(pwd),
      loginType: '5'
    };
    const path = new API().path({path: "token"});
    return this.httpService.post(path.baseURL, args, null, {
      'Content-Type': 'application/x-www-form-urlencoded'
    }).toPromise();
  }

  // 4A 登录
  async login() {
    // this.navCtrl.setRoot(TabsPage, {role: this.role})
    await this.storage.clearToken();
    // const path = new API().path({ path: "token" });
    this.loadingIndex = this.util.showLoading();
    this.userName = this.userName.trim();
    this.passWord = this.passWord.trim();
    return this.invokeLogin(this.userName, this.passWord)
      .then((data) => {
        this.util.hiddenLoading(this.loadingIndex);
        this.frequency = 1;
        console.log(data, "start login");
        if (data['access_token']) {
          this.saveUserData(data);
          this.storage.setToken("access_token", data['access_token']).subscribe(
            (res) => this.navCtrl.setRoot(TabsPage, {role: this.role}),
            (err) => this.navCtrl.setRoot(TabsPage, {role: this.role})
          );
          this.synService.openDatabase()
            .subscribe(() => {
              // TODO
            });
        } else {
          this.util.tip(data['message']);
        }
      }).catch((err) => {
        this.util.hiddenLoading(this.loadingIndex);
        if (this.frequency < 3) {
          ++this.frequency;
          this.login();
        } else {
          this.util.tip("网络连接失败，请重试");
        }
      });
  }


  getTestToken() {
    let user = {
      name: "user_cQdR2E", // 营销
      password: "mXFd4+Tq13MfSKSXI827iQPsNopZyxI9jLc27IEk7EodPh74MC7mRYmGVbfoHn56ijdIc7" +
      "avm9Kfkp3PZkvyztw2ECJVqSwkdLDTOQTSzyAusNOWwVJhRM5KC9pd8EdZEdhZkA1nB6MwvfKNwtFSrGDKIK7JZp7sso6Lvd1fn78=="
    };
    let formData = new FormData();
    formData.append("grant_type", "password");
    formData.append("loginAccount", user.name);
    formData.append("loginPassword", user.password);
    formData.append("loginType", '5');
    this.storage.clearToken();
    return this.httpService.post(new API().path({path: "token"}).baseURL, formData, null, {}).do((data) => {
      this.saveUserData(data);
      this.util.hiddenLoading();
    });
  }

  saveUserData(data) {
    this.role = data['role'];
    this.storage.set("access_token", data['access_token']);
    this.storage.set('refresh_token', data['refresh_token']);
    this.storage.set('qixinAccount', data['qixinAccount']);
    this.storage.set('loginAccount', data['loginAccount']);
    this.storage.set('loginUserName', data['userName']);
    window.localStorage.setItem('role', data['role']);
    window.localStorage.setItem('loginAccount', data['loginAccount']);
  }

}
